package com.cloudinnov.task.mq;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.cloudinnov.dao.ControlSolutionConfigDao;
import com.cloudinnov.dao.EquipmentsAttrDao;
import com.cloudinnov.dao.mongo.EmergencyPhoneMongoDBDao;
import com.cloudinnov.model.ControlSolutionConfig;
import com.cloudinnov.model.EmergecyPhone;
import com.cloudinnov.model.EquipmentsAttr;
import com.cloudinnov.utils.CommonUtils;
import com.cloudinnov.utils.JudgeNullUtil;
import com.cloudinnov.websocket.ControlSolutionDialogueWebsocket;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;

/**
 * 监听rabbitMQ发过来的紧急电话数据
 * @ClassName: CallMQConsumer
 * @Description: TODO
 * @author: ningmeng
 * @date: 2016年12月8日 下午2:09:47
 */
public class CallMQConsumer implements ChannelAwareMessageListener {
    static final String DEFAULT_CHARSET = "UTF-8";
    static final Logger LOG = LoggerFactory.getLogger(CallMQConsumer.class);
    static final long DELIVERIED_TAG = -1;
    @Autowired
    private EmergencyPhoneMongoDBDao emergencyPhoneMongoDBDao;
    @Autowired
    private EquipmentsAttrDao equipmentsAttrDao;
    @Autowired
    private ControlSolutionConfigDao controlSolutionConfigDao;

    @Override
    public void onMessage(Message message, Channel channel) throws IOException {
        LOG.debug("entering  OnMessage, data :{}", new String(message.getBody()));
        String receiveMsg = null;
        try {
            receiveMsg = new String(message.getBody(), DEFAULT_CHARSET);
            if (CommonUtils.isNotEmpty(receiveMsg)) {
                EmergecyPhone emergecyPhone = JSON.parseObject(receiveMsg, EmergecyPhone.class);
                emergencyPhoneMongoDBDao.save(emergecyPhone);
                if (CommonUtils.isEmpty(emergecyPhone.getPhoneId())) {
                    LOG.error("EmergecyPhone information useless,please write PhoneId, data: {}", emergecyPhone);
                    CommonUtils.writeStringToFile(System.getProperty("catalina.base") + File.separator + "data"
                            + File.separator + "calldata.txt", receiveMsg + "\r\n");// 写入文件保存
                    return;
                }
                EquipmentsAttr equAttr = new EquipmentsAttr();
                equAttr.setCustomTag(EmergecyPhone.PHONE_ID);
                equAttr.setValue(emergecyPhone.getPhoneId());
                List<EquipmentsAttr> equAttrs = equipmentsAttrDao.selectEquipmentByCustomTagAndValue(equAttr);
                if (JudgeNullUtil.iList(equAttrs)) {// 查询设备所在的所有群控方案
                    emergecyPhone.setEquipmentCode(equAttrs.get(0).getEquipmentCode());
                    emergecyPhone.setCategoryCode(equAttrs.get(0).getCategoryCode());
                    ControlSolutionConfig record = new ControlSolutionConfig();
                    record.setEquipmentCode(equAttrs.get(0).getEquipmentCode());
                    List<ControlSolutionConfig> list = controlSolutionConfigDao
                            .selectListByControlSolutionEquCode(record);
                    List<ControlSolutionConfig.Config> configs;
                    List<ControlSolutionConfig> data = new ArrayList<>();
                    for (ControlSolutionConfig controlSolutionConfig : list) {
                        List<ControlSolutionConfig> controlSolutionConfigs = controlSolutionConfigDao
                                .selectListBySolutionCode(controlSolutionConfig);
                        for (ControlSolutionConfig config : controlSolutionConfigs) {
                            configs = new ArrayList<>();
                            if (CommonUtils.isNotEmpty(config.getConfig())) {
                                configs.addAll(JSON.parseArray(config.getConfig(), ControlSolutionConfig.Config.class));
                            }
                            if (JudgeNullUtil.iList(configs)) {
                                config.setTextConfig(configs);
                                data.add(config);
                            }
                        }
                    }
                    Map<String, Object> webSocketContent = new HashMap<String, Object>();
                    webSocketContent.put("data", emergecyPhone);
                    webSocketContent.put("list", data);
                    ObjectMapper mapper = new ObjectMapper();
                    mapper.setSerializationInclusion(Include.NON_NULL);
                    sendMesssageToDialogueWebSocket(mapper.writeValueAsString(webSocketContent));
                }
            }
        } catch (UnsupportedEncodingException | JsonProcessingException e1) {
            LOG.error("Subscribe fault data is error, data: {}, error: {}", message, e1);
        } finally {
            long deliveryTag = message.getMessageProperties().getDeliveryTag();
            if (deliveryTag != DELIVERIED_TAG) {
                channel.basicAck(deliveryTag, false);
                message.getMessageProperties().setDeliveryTag(DELIVERIED_TAG);
                LOG.info("revice and ack msg: " + (receiveMsg == null ? message : receiveMsg));
            }
        }
    }
    private void sendMesssageToDialogueWebSocket(String content) {
        // 遍历所有连接客户工单WebSocket 推送对话
        Iterator<Map.Entry<String, ControlSolutionDialogueWebsocket>> controlSolutionDialogueWebsocket = ControlSolutionDialogueWebsocket.webSocketMap
                .entrySet().iterator();
        while (controlSolutionDialogueWebsocket.hasNext()) {
            Map.Entry<String, ControlSolutionDialogueWebsocket> controlSolutionDialogueEntry = controlSolutionDialogueWebsocket
                    .next();
            try {
                controlSolutionDialogueEntry.getValue().sendMessage(content);
            } catch (IOException e) {
            }
        }
    }
}
